<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div class="flex flex-col h-screen md:flex-row bg-gray-50 dark:bg-gray-900 gap-4 overflow-hidden">
				<!-- 左侧面板: 控制区域 -->
				<div class="flex-shrink-0 flex flex-col overflow-y-auto p-5 w-full md:w-1/4 min-w-[280px] bg-white dark:bg-gray-800 shadow-sm rounded-lg border border-gray-200 dark:border-gray-700">
					<div class="mb-5">
						<div class="flex justify-between items-center">
							<label class="text-sm font-semibold text-gray-700 dark:text-gray-300">模型</label>
							<div class="flex-grow ml-4">
								<ModelList ref="modelListComponent" :model-type="['Image']" @change="handleModelChange" />
							</div>
						</div>
					</div>

					<!-- 图片尺寸选择区域 -->
					<div class="mb-6">
						<label class="block mb-3 text-sm font-semibold text-gray-700 dark:text-gray-300">图片尺寸</label>
						<div class="grid grid-cols-3 gap-3">
							<div
								v-for="size in imageSizes"
								:key="size.value"
								@click="selectedImageSize = size.value"
								:class="[
									'flex relative justify-center items-center p-2 border rounded-lg cursor-pointer transition-all duration-200',
									selectedImageSize === size.value
										? 'bg-blue-50 dark:bg-blue-900/20 border-blue-500 dark:border-blue-400 text-blue-600 dark:text-blue-400 ring-2 ring-blue-200 dark:ring-blue-800'
										: 'bg-white dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600',
								]"
							>
								<div class="flex flex-col justify-center items-center py-1 w-full">
									<div class="overflow-hidden relative mb-2 w-12 h-8 rounded border border-gray-300 dark:border-gray-500 border-dashed">
										<img v-if="size.iconName" :src="getIconUrl(size.iconName)" :alt="size.label" class="object-contain w-full h-full" />
									</div>
									<span class="text-xs font-medium">{{ size.label }}</span>
								</div>
							</div>
						</div>
					</div>

					<div class="space-y-5">
						<!-- 图片数量滑块 -->
						<div>
							<div class="flex justify-between mb-2">
								<label class="text-sm font-semibold text-gray-700 dark:text-gray-300">图片数量</label>
								<span class="text-sm font-medium text-gray-600 dark:text-gray-400">{{ numberOfImages }}</span>
							</div>
							<el-slider v-model="numberOfImages" :min="1" :max="4" class="mx-1"></el-slider>
						</div>

						<!-- 随机种子输入框 -->
						<div>
							<label class="block mb-2 text-sm font-semibold text-gray-700 dark:text-gray-300">种子</label>
							<div class="flex items-center">
								<el-input v-model="seed" placeholder="随机种子" class="flex-grow mr-2"></el-input>
								<el-button
									:icon="RefreshRight"
									@click="randomizeSeed"
									class="flex-shrink-0 transition-transform duration-300 hover:rotate-180"
								></el-button>
							</div>
						</div>

						<!-- 推理步数滑块 -->
						<div>
							<div class="flex justify-between mb-2">
								<label class="text-sm font-semibold text-gray-700 dark:text-gray-300">推理步数</label>
								<span class="text-sm font-medium text-gray-600 dark:text-gray-400">{{ inferenceSteps }}</span>
							</div>
							<el-slider v-model="inferenceSteps" :min="1" :max="100" :step="1" class="mx-1"></el-slider>
						</div>

						<!-- 引导强度滑块 -->
						<div>
							<div class="flex justify-between mb-2">
								<label class="text-sm font-semibold text-gray-700 dark:text-gray-300">引导强度</label>
								<span class="text-sm font-medium text-gray-600 dark:text-gray-400">{{ guidanceScale }}</span>
							</div>
							<el-slider v-model="guidanceScale" :min="1" :max="20" :step="0.1" class="mx-1"></el-slider>
						</div>

						<!-- 反向提示词输入框 -->
						<div>
							<label class="block mb-2 text-sm font-semibold text-gray-700 dark:text-gray-300">反向提示词</label>
							<el-input type="textarea" :rows="3" v-model="negativePrompt" placeholder="不想在图片中看到的内容" class="w-full rounded-lg"></el-input>
						</div>

						<!-- 上传参考图片 -->
						<div>
							<div class="flex justify-between items-center mb-3">
								<label class="text-sm font-semibold text-gray-700 dark:text-gray-300">
									参考图片 
									<span v-if="!isOpenRouterModel" class="text-red-500">*</span>
									<span v-if="isOpenRouterModel" class="text-xs text-gray-500 ml-1">(最多4张)</span>
								</label>
								<div v-if="hasUploadedImages" class="flex gap-2">
									<el-tooltip content="清空所有图片" placement="top">
										<el-button type="danger" size="small" plain circle icon="Delete" @click="handleAllImagesRemove" />
									</el-tooltip>
								</div>
							</div>
							
							<!-- 多图片预览区域 (OpenRouter) -->
							<div v-if="isOpenRouterModel && uploadedImages.length > 0" class="mb-3">
								<div class="grid grid-cols-2 gap-3">
									<div
										v-for="(image, index) in uploadedImages"
										:key="image.id"
										class="relative group"
									>
										<div class="relative overflow-hidden bg-gray-50 dark:bg-gray-700 rounded-xl border-2 border-gray-200 dark:border-gray-600 shadow-sm">
											<img 
												:src="image.base64" 
												:alt="`参考图片 ${index + 1}`" 
												class="w-full h-24 object-cover transition-transform duration-300 group-hover:scale-105"
											/>
											<!-- 悬浮遮罩 -->
											<div class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center">
												<div class="flex gap-2">
													<el-button type="danger" size="small" circle icon="Delete" @click="handleSingleImageRemove(image.id)" />
													<el-button type="info" size="small" circle icon="ZoomIn" @click="previewSingleImage(image.base64)" />
												</div>
											</div>
											<!-- 图片序号标签 -->
											<div class="absolute top-2 left-2">
												<el-tag size="small" effect="dark" class="backdrop-blur-sm">
													<el-icon class="mr-1"><Picture /></el-icon>
													{{ index + 1 }}
												</el-tag>
											</div>
										</div>
									</div>
								</div>
							</div>
							
							<!-- 单图片预览区域 (非OpenRouter) -->
							<div v-else-if="!isOpenRouterModel && uploadedImageBase64" class="relative group mb-3">
								<div class="relative overflow-hidden bg-gray-50 dark:bg-gray-700 rounded-xl border-2 border-gray-200 dark:border-gray-600 shadow-sm">
									<img 
										:src="uploadedImageBase64" 
										alt="参考图片" 
										class="w-full h-24 object-cover transition-transform duration-300 group-hover:scale-105"
									/>
									<!-- 悬浮遮罩 -->
									<div class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center">
										<div class="flex gap-2">
											<el-button type="danger" size="small" circle icon="Delete" @click="handleImageRemove" />
											<el-button type="info" size="small" circle icon="ZoomIn" @click="previewImage" />
										</div>
									</div>
									<!-- 图片信息标签 -->
									<div class="absolute top-2 left-2">
										<el-tag size="small" effect="dark" class="backdrop-blur-sm">
											<el-icon class="mr-1"><Picture /></el-icon>
											参考图片
										</el-tag>
									</div>
								</div>
							</div>
							
							<!-- 上传区域 -->
							<div v-if="!hasUploadedImages || (isOpenRouterModel && uploadedImages.length < 4)">
								<el-upload
									ref="uploadRef"
									:auto-upload="false"
									:limit="isOpenRouterModel ? 4 : 1"
									:on-change="handleImageUpload"
									:show-file-list="false"
									accept="image/png,image/jpg,image/jpeg,image/webp,image/gif,image/bmp,image/tiff"
									drag
									:disabled="isUploading"
									multiple
									class="h-[80px]"
								>
									<div class="flex flex-col items-center justify-center py-2 px-4 text-center h-full">
										<el-icon class="mb-1 text-2xl" :class="isUploading ? 'text-blue-500' : 'text-gray-400 dark:text-gray-500'">
											<Loading v-if="isUploading" class="animate-spin" />
											<UploadFilled v-else />
										</el-icon>
										<div class="mb-1">
											<span v-if="isUploading" class="text-blue-500 font-medium text-sm">正在处理图片...</span>
											<template v-else>
												<span class="text-primary font-medium text-sm">点击上传</span>
												<span class="text-gray-500 dark:text-gray-400 ml-1 text-sm">或拖拽图片到此区域</span>
											</template>
										</div>
										<div class="text-xs text-gray-400 dark:text-gray-500">
											<template v-if="isOpenRouterModel">
												支持 PNG 格式，单文件不超过 2MB ({{ uploadedImages.length }}/4)
											</template>
											<template v-else>
												支持 PNG、JPG、WEBP、GIF 等格式，单文件不超过 2MB
											</template>
										</div>
									</div>
								</el-upload>
							</div>
								
							<!-- 错误提示 -->
							<div v-if="!hasUploadedImages && !isOpenRouterModel" class="flex items-center mt-2 text-xs text-red-500">
								<el-icon class="mr-1"><WarningFilled /></el-icon>
								请上传参考图片
							</div>
						</div>
					</div>
				</div>

				<!-- 中间面板: 图片显示和提示词输入区域 -->
				<div class="flex flex-col flex-grow p-5 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 min-h-0 relative overflow-hidden">
					<!-- 图片显示区域 - 固定高度 -->
					<div class="flex overflow-hidden relative flex-col bg-gray-50 dark:bg-gray-700 rounded-xl border border-gray-200 dark:border-gray-600 h-[400px] flex-shrink-0">
						<div v-if="selectedHistoryImage" class="flex justify-center items-center p-2 w-full h-full">
							<img
								:src="baseURL + selectedHistoryImage"
								alt="History Image"
								class="object-contain max-w-full max-h-full rounded-lg shadow-md h-[400px]"
							/>
							<!-- 操作按钮组 -->
							<div class="absolute top-3 right-3 flex gap-2">
								<el-tooltip content="下载图片" placement="top">
									<el-button
										size="small"
										type="primary"
										circle
										@click="downloadSingleImage(selectedHistoryImage)"
										icon="Download"
									></el-button>
								</el-tooltip>
								<el-button
									class="backdrop-blur-sm bg-white/80 hover:bg-white"
									size="small"
									type="default"
									circle
									@click="selectedHistoryImage = null"
									icon="Close"
								></el-button>
							</div>
						</div>
						<div v-else-if="generatedImageUrls.length > 0" class="w-full h-full relative">
							<!-- 下载按钮组 -->
							<div class="absolute top-3 right-3 flex gap-2 z-10">
								<el-tooltip content="下载当前图片" placement="top">
									<el-button
										size="small"
										type="primary"
										circle
										@click="downloadCurrentImage"
										icon="Download"
									></el-button>
								</el-tooltip>

							</div>
							
							<el-carousel
								:initial-index="currentImageIndex"
								height="100%"
								arrow="always"
								indicator-position="outside"
								@change="handleCarouselChange"
								class="h-full image-carousel"
							>
								<el-carousel-item v-for="(url, index) in generatedImageUrls" :key="index" class="flex justify-center items-center h-full">
									<div class="flex justify-center items-center p-4 w-full h-full image-container">
										<img :src="baseURL + url" alt="Generated Image" class="object-contain max-w-full max-h-full rounded-lg shadow-md h-[600px]" />
									</div>
								</el-carousel-item>
							</el-carousel>
						</div>
						<div v-else-if="isGenerating" class="flex flex-col justify-center items-center h-full">
							<el-icon class="text-blue-500 animate-spin" size="48"><Loading /></el-icon>
							<span class="mt-4 font-medium text-gray-600 dark:text-gray-400">正在生成图片...</span>
						</div>
						<div v-else class="flex justify-center items-center h-full">
							<div class="p-8 text-center">
								<span class="block mb-2 text-gray-400 dark:text-gray-500">图片将在这里显示</span>
								<span class="text-xs text-gray-400 dark:text-gray-500">输入提示词并点击生成按钮</span>
							</div>
						</div>
					</div>

					<!-- 示例提示词区域 - 固定高度 -->
					<div v-if="!selectedHistoryImage" class="flex-shrink-0 mb-4">
						<div class="flex justify-between items-center mb-3">
							<h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300">示例提示词</h3>
							<div class="flex items-center gap-2">
								<el-tooltip content="点击使用示例提示词" placement="top">
									<el-icon class="text-gray-400 dark:text-gray-500 cursor-help hover:text-gray-600 dark:hover:text-gray-400"><InfoFilled /></el-icon>
								</el-tooltip>
								<el-tooltip :content="showExamplePrompts ? '隐藏示例提示词' : '显示示例提示词'" placement="top">
									<el-icon 
										@click="showExamplePrompts = !showExamplePrompts" 
										class="text-gray-400 dark:text-gray-500 cursor-pointer hover:text-gray-600 dark:hover:text-gray-400 transition-colors"
									>
										<component :is="showExamplePrompts ? 'ArrowUp' : 'ArrowDown'" />
									</el-icon>
								</el-tooltip>
							</div>
						</div>
						<div v-show="showExamplePrompts" class="grid grid-cols-1 gap-2 pb-1 custom-scrollbar overflow-y-auto ">
							<div
								v-for="example in examplePrompts"
								:key="example"
								@click="prompt = example"
								class="flex items-center h-[40px] p-3 bg-white dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 transition-all duration-200 cursor-pointer hover:bg-blue-50 dark:hover:bg-blue-900/20 hover:border-blue-300 dark:hover:border-blue-500"
							>
								<el-icon class="mr-3 text-blue-500"><ChatLineRound /></el-icon>
								<div class="overflow-hidden">
									<p class="text-sm truncate text-gray-800 dark:text-gray-200">{{ truncateText(example, 60) }}</p>
								</div>
							</div>
						</div>
					</div>

					<!-- 提示词输入区域 - 绝对定位固定在底部 -->
					<div class="absolute bottom-5 left-5 right-5 z-20">
						<div class="flex flex-col items-center p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-600 shadow-lg backdrop-blur-sm">
							<div v-if="selectedHistoryImage" class="mb-3 w-full text-center">
								<el-tag type="info" effect="light" size="small" class="px-3 py-1 mb-1">
									<el-icon class="mr-1"><InfoFilled /></el-icon>您正在查看历史图片，可以编辑提示词重新生成
								</el-tag>
							</div>
							<div class="flex items-center w-full">
								<el-input
									v-model="prompt"
									placeholder="请输入你的创意指令... "
									class="flex-grow mr-4 prompt-input"
									@keyup.enter.prevent="handlePromptEnter"
									autosize
									type="textarea"
									:maxlength="500"
									:input-style="{
										border: 'none',
										boxShadow: 'none',
										padding: '12px 0px',
										lineHeight: '1.5',
										resize: 'none',
										backgroundColor: selectedHistoryImage ? 'var(--el-fill-color-blank)' : 'transparent',
									}"
									resize="none"
								>
								</el-input>
								<el-button
									circle
									type="primary"
									@click="generateImage"
									:loading="isGenerating"
									class="flex justify-center items-center w-14 h-14 min-w-[3.5rem] min-h-[3.5rem] rounded-full shadow-md transition-all duration-300 hover:shadow-lg transform hover:scale-105"
									:disabled="!prompt.trim()"
								>
									<el-icon size="26"><Promotion /></el-icon>
								</el-button>
							</div>
						</div>
					</div>
				</div>

				<!-- 右侧面板: 历史记录 -->
				<div class="flex-shrink-0 w-full md:w-1/4">
					<HistoryPanel
						ref="historyPanelRef"
						title="生成历史"
						material-type="Image"
						thumbnailAlt="Generated Image"
						@item-click="handleHistoryItemClick"
						:default-page-size="pageSize"
						:show-time-column="true"
						class="h-full"
					/>
				</div>
			</div>
		</div>
		
		<!-- 图片预览弹窗 -->
		<el-image-viewer 
			v-if="showImagePreview"
			:url-list="previewImageList"
			:initial-index="0"
			@close="showImagePreview = false"
		/>
	</div>
</template>



<script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue';
import { RefreshRight, Promotion, Loading, InfoFilled, ChatLineRound, Close, UploadFilled, Picture, Delete, ZoomIn, WarningFilled, Download, ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import ModelList from './components/widgets/modelList.vue';
import HistoryPanel, { type HistoryItem } from './components/widgets/historyPanel.vue';
import { genImage } from '/@/api/knowledge/aiGen';
import { Local } from '/@/utils/storage';

// Import SVG icons
import imageSize11 from '/@/assets/ai/images/image-size-1-1.svg';
import imageSize12 from '/@/assets/ai/images/image-size-1-2.svg';
import imageSize32 from '/@/assets/ai/images/image-size-3-2.svg';
import imageSize34 from '/@/assets/ai/images/image-size-3-4.svg';
import imageSize169 from '/@/assets/ai/images/image-size-16-9.svg';
import imageSize916 from '/@/assets/ai/images/image-size-9-16.svg';

// SVG icon mapping
const iconMap: Record<string, string> = {
	'image-size-1-1': imageSize11,
	'image-size-1-2': imageSize12,
	'image-size-3-2': imageSize32,
	'image-size-3-4': imageSize34,
	'image-size-16-9': imageSize169,
	'image-size-9-16': imageSize916,
};

// Get the baseURL from environment variables
const baseURL = import.meta.env.VITE_API_URL || '';

// 获取图标URL的辅助函数
const getIconUrl = (iconName: string) => {
	return iconMap[iconName] || '';
};

// 文本截断的辅助函数
const truncateText = (text: string, maxLength: number) => {
	return text?.length > maxLength ? text.substring(0, maxLength) + '...' : text || '';
};

// 左侧面板: 控制数据
const modelListComponent = ref<any>(null); // 模型选择组件引用
const imageSizes = ref([
	{ label: '1:1', value: '1024x1024', iconName: 'image-size-1-1' }, // 方形图片
	{ label: '1:2', value: '720x1440', iconName: 'image-size-1-2' }, // 长形竖图
	{ label: '3:2', value: '960x1280', iconName: 'image-size-3-2' }, // 电影海报比例
	{ label: '3:4', value: '768x1024', iconName: 'image-size-3-4' }, // 肖像/人像比例
	{ label: '16:9', value: '1024x576', iconName: 'image-size-16-9' }, // 宽屏比例
	{ label: '9:16', value: '720x1280', iconName: 'image-size-9-16' }, // 手机屏幕比例
]);

const selectedImageSize = ref('1024x1024'); // 默认图片尺寸为1:1
const numberOfImages = ref(1); // 默认生成图片数量
const seed = ref(''); // 随机种子值
const inferenceSteps = ref(25); // 推理步数，步数越大，生成质量越高但耗时更长
const guidanceScale = ref(7.5); // 引导强度，值越高越忠于提示词
const negativePrompt = ref<string | null>(null); // 反向提示词，指定不希望在图像中出现的内容
const uploadedImageBase64 = ref<string | null>(null); // 上传图片的Base64编码（兼容旧版本）
const uploadedImageFile = ref<File | null>(null); // 上传的图片文件对象（兼容旧版本）
const uploadedImages = ref<Array<{ base64: string; file: File; id: string }>>([]); // 多张上传图片数组
const uploadRef = ref(); // 上传组件引用
const isUploading = ref(false); // 上传状态

// 右侧面板: 数据
const generatedImageUrl = ref<string>(''); // 当前显示的生成图片URL
const generatedImageUrls = ref<string[]>([]); // 所有生成的图片URL数组
const currentImageIndex = ref(0); // 当前查看的图片索引
const prompt = ref(''); // 提示词输入
const isGenerating = ref(false); // 是否正在生成图片
const selectedHistoryImage = ref<string | null>(null); // 选中的历史图片URL
const examplePrompts = ref([
	// 示例提示词列表
	'埃菲尔铁塔被包裹在彩色丝绸中，日落时分，高清摄影，逼真细节，金色光芒',
	'场景由三个物体组成：一本古老的书籍，一盏复古油灯和一只沉睡的猫，柔和的光线，写实风格',
	'古老的战场，虽然战争已经结束，但残留的盔甲和武器依然散落，薄雾笼罩，史诗般的氛围，8K渲染',
]);

// 历史记录和分页相关数据
const pageSize = ref(10);



// 计算属性：判断当前选中的模型是否为 OpenRouter 类型
const isOpenRouterModel = ref(false)
const showExamplePrompts = ref(true) // 控制示例提示词的显示/隐藏

const checksOpenRouterModel = () => {
	const selectedModel = Local.get(`selectedAiModel:Image`);
	isOpenRouterModel.value =  selectedModel?.provider === 'OpenRouter';
};

// 计算属性：判断是否有上传的图片
const hasUploadedImages = computed(() => {
	return isOpenRouterModel.value 
		? uploadedImages.value.length > 0 
		: uploadedImageBase64.value !== null;
});

// 监听模型类型变化，自动清理图片
watch(isOpenRouterModel, (newValue, oldValue) => {
	if (newValue !== oldValue) {
		// 模型类型发生变化时，清理所有图片
		uploadedImages.value = [];
		uploadedImageBase64.value = null;
		uploadedImageFile.value = null;
		
		if (newValue) {
			ElMessage.info('已切换到 OpenRouter 模型，支持上传最多4张PNG格式的参考图片');
		} else {
			ElMessage.info('已切换到其他模型，需要上传1张PNG格式的参考图片');
		}
	}
});

// 左侧面板: 方法
// 生成随机种子
const randomizeSeed = () => {
	seed.value = String(Math.floor(Math.random() * 1000000000));
};

// 处理图片上传
const handleImageUpload = (file: any) => {
	const rawFile = file.raw;
	
	console.log('上传文件信息:', {
		name: rawFile?.name,
		type: rawFile?.type,
		size: rawFile?.size,
		isOpenRouter: isOpenRouterModel.value,
		currentImageCount: uploadedImages.value.length
	});
	
	// 验证文件类型 - 支持多种图片格式
	const allowedTypes = [
		'image/png', 
		'image/jpg', 
		'image/jpeg', 
		'image/webp', 
		'image/gif', 
		'image/bmp', 
		'image/tiff'
	];
	
	if (!rawFile || !rawFile.type || !allowedTypes.includes(rawFile.type)) {
		ElMessage.error('请上传支持的图片格式（PNG、JPG、JPEG、WEBP、GIF、BMP、TIFF）');
		return false;
	}
	
	// 验证文件大小（限制为2MB）
	const maxSize = 2 * 1024 * 1024; // 2MB
	if (rawFile.size > maxSize) {
		ElMessage.error('图片文件大小不能超过2MB');
		return false;
	}
	
	// OpenRouter 模型检查图片数量限制
	if (isOpenRouterModel.value && uploadedImages.value.length >= 4) {
		ElMessage.error('OpenRouter 模型最多支持上传4张参考图片');
		return false;
	}
	
	// 显示上传状态
	isUploading.value = true;
	
	const reader = new FileReader();
	reader.onload = (e) => {
		if (e.target && e.target.result) {
			const base64Result = e.target.result.toString();
			
			if (isOpenRouterModel.value) {
				// OpenRouter 模型：添加到多图片数组
				const imageId = `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
				uploadedImages.value.push({
					id: imageId,
					base64: base64Result,
					file: rawFile
				});
				ElMessage.success(`图片上传成功！已上传 ${uploadedImages.value.length}/4 张图片`);
			} else {
				// 非 OpenRouter 模型：单图片模式
				uploadedImageBase64.value = base64Result;
				uploadedImageFile.value = rawFile;
				ElMessage.success(`图片上传成功！文件大小：${(rawFile.size / 1024 / 1024).toFixed(2)}MB`);
			}
			
			isUploading.value = false;
		}
	};
	
	reader.onerror = () => {
		isUploading.value = false;
		ElMessage.error('图片读取失败，请重试');
	};
	
	reader.readAsDataURL(rawFile);
	return false; // 阻止自动上传
};

// 处理图片移除（兼容旧版本）
const handleImageRemove = () => {
	uploadedImageFile.value = null;
	uploadedImageBase64.value = null;
};

// 处理单张图片移除（OpenRouter）
const handleSingleImageRemove = (imageId: string) => {
	const index = uploadedImages.value.findIndex(img => img.id === imageId);
	if (index > -1) {
		uploadedImages.value.splice(index, 1);
		ElMessage.success('图片删除成功');
	}
};

// 处理清空所有图片
const handleAllImagesRemove = () => {
	if (isOpenRouterModel.value) {
		uploadedImages.value = [];
		ElMessage.success('已清空所有图片');
	} else {
		handleImageRemove();
		ElMessage.success('图片删除成功');
	}
};

// 预览图片状态
const showImagePreview = ref(false);
const previewImageList = ref<string[]>([]);

// 预览图片（兼容旧版本）
const previewImage = () => {
	if (uploadedImageBase64.value) {
		previewImageList.value = [uploadedImageBase64.value];
		showImagePreview.value = true;
	}
};

// 预览单张图片（OpenRouter）
const previewSingleImage = (base64: string) => {
	previewImageList.value = [base64];
	showImagePreview.value = true;
};

// 右侧面板: 方法
// 处理回车键按下事件
const handlePromptEnter = (event: KeyboardEvent) => {
	if (event.shiftKey) {
		// 允许Shift+Enter换行
		return;
	}
	generateImage(); // 直接回车则生成图片
};

// 历史面板引用
const historyPanelRef = ref<InstanceType<typeof HistoryPanel> | null>(null);

// 处理历史项目点击 - 新方法，适配historyPanel组件
const handleHistoryItemClick = (item: HistoryItem) => {
	if (item.localUrl) {
		// 显示历史图片
		selectedHistoryImage.value = item.localUrl;
		// 应用提示词
		prompt.value = item.prompt || '';
	} else {
		ElMessage.info('该记录没有图片');
	}
};

const handleModelChange = (model: any) => {
	checksOpenRouterModel();
};

// 生成图片的核心方法
const generateImage = async () => {
	if (!prompt.value.trim()) {
		ElMessage.warning('请输入提示词!');
		return;
	}
	
	// 验证参考图片
	if (!isOpenRouterModel.value && !uploadedImageBase64.value) {
		ElMessage.warning('请上传参考图片!');
		return;
	}

	isGenerating.value = true;
	generatedImageUrl.value = ''; // 清除之前的图片
	generatedImageUrls.value = []; // 清除之前的图片数组
	selectedHistoryImage.value = null; // 清除选中的历史图片
	currentImageIndex.value = 0; // 重置索引

	try {
		// 获取本地存储的选中模型
		const selectedModel = Local.get(`selectedAiModel:Image`);

		// 准备API调用参数
		const params: any = {
			model: selectedModel.name, // 选中的AI模型名称
			imageSize: selectedImageSize.value, // 图片尺寸
			batchSize: numberOfImages.value, // 生成图片数量
			seed: seed.value ? Number(seed.value) : undefined, // 随机种子
			numInferenceSteps: inferenceSteps.value, // 推理步数
			guidanceScale: guidanceScale.value, // 引导强度
			negativePrompt: negativePrompt.value || undefined, // 反向提示词
			prompt: prompt.value, // 正向提示词
		};

		// 处理参考图片 - 统一使用 images 数组格式
		if (isOpenRouterModel.value && uploadedImages.value.length > 0) {
			// OpenRouter 模型：传递多张图片
			params.images = uploadedImages.value.map(img => img.base64);
		} else if (!isOpenRouterModel.value && uploadedImageBase64.value) {
			// 非 OpenRouter 模型：传递单张图片，也使用数组格式
			params.image = uploadedImageBase64.value;
		}
		// 调用API生成图片
		const { data: imageUrls } = await genImage(params);
		if (imageUrls && imageUrls.length) {
			generatedImageUrls.value = imageUrls;
			generatedImageUrl.value = imageUrls[0]; // 设置第一张图片为当前显示
			currentImageIndex.value = 0; // 设置为第一张图片
			ElMessage.success('图片生成成功!');

			// 生成成功后刷新历史记录
			historyPanelRef.value?.refreshHistory();
		} else {
			ElMessage.error('图片生成失败, 请稍后重试');
		}
	} catch (error) {
		const errorMessage = error instanceof Error ? error.message : 'Unknown error';
		ElMessage.error(`生成图片时发生错误，请稍后重试: ${errorMessage}`);
	} finally {
		isGenerating.value = false; // 无论成功或失败，都重置生成状态
	}
};

// 处理轮播图当前图片
const handleCarouselChange = (index: number) => {
	currentImageIndex.value = index;
	generatedImageUrl.value = generatedImageUrls.value[index];
};

// 下载功能相关方法
/**
 * 下载单张图片
 * @param imageUrl 图片URL
 */
const downloadSingleImage = async (imageUrl: string) => {
	try {
		const fullUrl = baseURL + imageUrl;
		const response = await fetch(fullUrl);
		
		if (!response.ok) {
			throw new Error('下载失败');
		}
		
		const blob = await response.blob();
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		
		// 生成文件名
		const timestamp = Date.now();
		const fileName = `ai-image-${timestamp}.png`;
		
		link.href = url;
		link.download = fileName;
		document.body.appendChild(link);
		link.click();
		
		// 清理
		document.body.removeChild(link);
		window.URL.revokeObjectURL(url);
		
		ElMessage.success('图片下载成功！');
	} catch (error) {
		console.error('下载图片失败:', error);
		ElMessage.error('下载图片失败，请稍后重试');
	}
};

/**
 * 下载当前轮播图显示的图片
 */
const downloadCurrentImage = () => {
	if (generatedImageUrls.value.length > 0 && currentImageIndex.value >= 0) {
		const currentUrl = generatedImageUrls.value[currentImageIndex.value];
		downloadSingleImage(currentUrl);
	}
};



// 组件初始化
onMounted(() => {
	// 生成随机种子
	randomizeSeed();
	checksOpenRouterModel();
});
</script>